<!--
  -    Copyright (c) 2018-2025, cloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: cloud
  -->
<template>
  <div class="execution">
    <BasicContainer>
      <FyCurd
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @selection-change="selectionChange"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel"
        @row-click="handleCurrentRowChange">
        <template #menuLeft>
          <ElButton
            v-if="permissions.secretasset_secretasset_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel">
            导出
          </ElButton>
          <ElButton
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-upload"
            @click="$refs.excelUpload.show()">
            导入
          </ElButton>
          <ElButton
            v-if="permissions.secretasset_secretasset_print"
            class="filter-item"
            icon="el-icon-print"
            plain
            size="small"
            type="primary"
            @click="batchPrint">
            打印标签
          </ElButton>
          <ElButton
            v-if="permissions.secretasset_secretasset_del"
            class="filter-item"
            icon="el-icon-delele"
            plain
            size="small"
            type="primary"
            @click="batchDelete">
            批量删除
          </ElButton>
        </template>
      </FyCurd>
      <!--excel 模板导入 -->
      <ExcelUpload
        ref="excelUpload"
        title="涉密设备信息导入"
        :url="`${services.personnelService}secretasset/import`"
        :temp-url="`${services.personnelService}/secretasset/local/secretassettemplate.xlsx`"
        temp-name="涉密设备信息导入模板.xlsx"
        @refreshDataList="refreshChange" />

      <SelectPrintLabelSpecs ref="selectPrintLabelSpecs" :visible.sync="visibleSpecs" @confirm="confirm" />
    </BasicContainer>
  </div>
</template>

<script>
  import { fetchList, addObj, putObj, delObj, batchDeleteIds } from '@/api/asset/secretasset'
  import { tableOption } from '@/const/crud/asset/secretasset'
  import { mapState } from 'vuex'

  import SelectPrintLabelSpecs from '@/module/asset/secretasset/SelectPrintLabelSpecs'
  import { printSmallSecretLabels, printBigSecretLabels } from '@/util/label-print'
  import { getObj } from '@/api/admin/sys-public-param'
  import { services } from '@/config'

  export default {
    name: 'Secretasset',
    components: {
      SelectPrintLabelSpecs
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSizes: [20, 30, 40, 50, 100, 500, 1000],
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableRows: [],
        tableOption,
        visibleSpecs: false,
        printIp: '',
        services
      }
    },
    computed: {
      ...mapState('user', ['permissions']),
      permissionList() {
        return {
          addBtn: this.permissions.secretasset_secretasset_add,
          delBtn: this.permissions.secretasset_secretasset_del,
          printBtn: this.permissions.secretasset_secretasset_print,
          editBtn: this.permissions.secretasset_secretasset_edit
        }
      }
    },
    created() {
      this.init()
    },
    methods: {
      async init() {
        const res = await getObj('POSTEK_PRINT_IP')
        this.printIp = res.data.data
      },
      // 列表查询
      getList(page, params) {
        this.tableLoading = true
        fetchList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize
            },
            params,
            this.searchForm
          )
        )
          .then(response => {
            this.tableData = response.data.data.records
            this.page.total = response.data.data.total
            this.tableLoading = false
          })
          .catch(() => {
            this.tableLoading = false
          })
      },
      // 删除
      handleDel: function (row, index) {
        this.$confirm(`是否确认删除ID为${row.id}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function () {
            return delObj(row.id)
          })
          .then(data => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
      },
      // 更新
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
          .then(data => {
            this.$message.success('修改成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 保存
      handleSave: function (row, done, loading) {
        addObj(row)
          .then(data => {
            this.$message.success('添加成功')
            done()
            this.getList(this.page)
          })
          .catch(() => {
            loading()
          })
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      selectionChange(rows) {
        this.tableRows = rows
      },
      batchPrint() {
        if (this.tableRows.length === 0) {
          this.$message.warning('请选择打印标签的涉密设备！')
          return
        }
        this.visibleSpecs = true
      },
      batchDelete() {
        if (this.tableRows.length === 0) {
          this.$message.warning('请选择要删除的数据！')
          return
        }
        const ids = []
        this.tableRows.forEach(item => {
          ids.push(item.id)
        })
        this.$confirm(`是否确认删"${ids.length} "条数据，提示`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function () {
            return batchDeleteIds(ids)
          })
          .then(response => {
            if (response.data.data) {
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
            this.getList(this.page)
          })
      },
      handleCurrentRowChange(val) {
        this.$refs.crud.toggleSelection([val])
      },
      //  导出excel
      exportExcel() {
        const exportFileName = `涉密台账设备信息_${this.$dateFormat(new Date())}.xlsx`
        this.$downBlobFile(`${services.personnelService}secretasset/export`, this.searchForm, exportFileName)
      },
      confirm(printSpecs) {
        this.visibleSpecs = false
        if (printSpecs === '1') {
          this.printSmallSecretLabels(true, this.formatRows(true, this.tableRows, '广海局涉密设备标识')) // 32*20涉密
        } else if (printSpecs === '2') {
          this.printSmallSecretLabels(true, this.formatRows(true, this.tableRows, '广海局固定资产标签卡')) // 30*20非涉密
        } else if (printSpecs === '3') {
          this.printBigSecretLabels(true, this.formatRows(true, this.tableRows, '广海局涉密设备标识')) // 50*30涉密
        } else if (printSpecs === '4') {
          this.printBigSecretLabels(true, this.formatRows(true, this.tableRows, '广海局固定资产标签卡')) // 50*30非涉密
        }
      },
      // 50*30
      printBigSecretLabels(isSecret, rows) {
        const loading = this.$loading({
          lock: true,
          text: '标签打印中,请稍后。。。',
          spinner: 'el-icon-loading'
        })

        printBigSecretLabels({
          url: this.printIp,
          rows,
          transfer(row) {
            return row
          },
          cb(res) {
            // console.log(res)
          },
          complete() {
            loading.close()
          }
        })
      },
      // 30*20
      printSmallSecretLabels(isSecret, rows) {
        const loading = this.$loading({
          lock: true,
          text: '标签打印中,请稍后。。。',
          spinner: 'el-icon-loading'
        })
        printSmallSecretLabels(
          {
            url: this.printIp,
            rows,
            transfer(row) {
              return row
            },
            cb(res) {
              // console.log(res)
            },
            complete() {
              loading.close()
            }
          },
          isSecret
        )
      },
      formatRows(isSecret, rows, title) {
        const printRows = []
        rows.forEach(row => {
          const printRow = {
            unitName: '广海局固定资产标签卡', // 所属部门名称
            name: row.name, // 设备名称
            isSecret,
            secret: row.level, // 密级
            code: row.diviceNumber, //  设备编码
            mode: row.model, // 品牌型号
            department: row.belongtoName,
            user: row.principalName, // 使用人
            address: row.locationName, // 放置地点
            time: row.enableDate // 启用时间
          }
          // 涉密删除用途
          if (isSecret) {
            printRow.unitName = '广海局涉密设备标识'
            delete printRow.purpose
          }
          printRow.unitName = title
          printRows.push(printRow)
        })
        return printRows
      }
    }
  }
</script>
